package com.sudoku.background;

import java.util.ArrayList;

import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.sudoku.utility.Constants;
import com.sudoku.utility.Pair;

public class BackgroundManager implements Constants {

	private ArrayList<Pair<Integer, Vector2>> fallingNumbers;
	private ArrayList<Pair<Integer, Vector2>> deleted;
	private float timer;
	private float dropTime;
	public float speed;

	public BackgroundManager() {
		fallingNumbers = new ArrayList<Pair<Integer, Vector2>>();
		deleted = new ArrayList<Pair<Integer, Vector2>>();
		newDropTime();
		populateScreen();
		speed = 40;
	}
	
	private void populateScreen() {
		int num=MathUtils.random(5, 10);
		for(int i=0; i<num; i++){
			fallingNumbers.add(new Pair<Integer, Vector2>(MathUtils.random(1, 9), new Vector2(MathUtils.random(0, ACTUAL_VIRTUAL_WIDTH),
					MathUtils.random(0,ACTUAL_VIRTUAL_HEIGHT))));
		}
		
	}

	public void render(SpriteBatch uiBatch, BitmapFont font) {
		for (Pair<Integer, Vector2> pair : fallingNumbers) {
			font.draw(uiBatch, "" + pair.getFirst(), pair.getSecond().x, pair.getSecond().y);
		}
	}

	public void update(float delta) {
		timer += delta;
		if (timer > dropTime) {
			newDropTime();
			timer = 0;
			fallingNumbers.add(new Pair<Integer, Vector2>(MathUtils.random(1, 9), new Vector2(MathUtils.random(0, ACTUAL_VIRTUAL_WIDTH),
					ACTUAL_VIRTUAL_HEIGHT*1.1f)));
		}
		for (Pair<Integer, Vector2> pair : fallingNumbers) {
			pair.setSecond(pair.getSecond().set(pair.getSecond().x, pair.getSecond().y - speed * delta));
			if (pair.getSecond().y < 0) {
				deleted.add(pair);
			}
		}
		fallingNumbers.removeAll(deleted);
		deleted.clear();
	}

	private void newDropTime() {
		dropTime = 2 * MathUtils.random() * 2;

	}
}
